package LC;

/**
 * https://leetcode.com/problems/path-sum/description/
 * Given a binary tree and a sum, determine if the tree has a root-to-leaf path
 * such that adding up all the values along the path equals the given sum.
 * For example:
 * Given the below binary tree and sum = 22,
 */
public class LC_112_PathSum_Recur_BinaryTree {

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(-1);
        boolean f = Solution.hasPathSum(root, 2);
        System.out.println(f);
    }

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }

    static class Solution {
        private static boolean checkPathSum(TreeNode root, int sum, int now) {
            if (root == null) return false;
            now += root.val;
            if (root.left == null && root.right == null) return sum == now;
            return checkPathSum(root.left, sum, now) || checkPathSum(root.right, sum, now);
        }

        static boolean hasPathSum(TreeNode root, int sum) {
            return root != null && checkPathSum(root, sum, 0);
        }
    }
}